#!/usr/bin/env python
# coding: utf-8

# In[ ]:
import os
import csv

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

# In[]
#产生存储路径与文件
import os
def generpath(path):
    if not os.path.exists(path):
        os.makedirs(path)
def generfile(path,filename,m):
    if not os.path.exists(path+filename):
        order = [x for x in range(1,m+1)]
        dataframe = pd.DataFrame({"order":order})
        dataframe.to_csv(path+filename,sep=',')
# In[58]:
#存储预测值
def datasave(savepath,saveindex,y_test_pre):
    sdata =pd.read_csv(savepath)
    sdata= pd.DataFrame(sdata)
    y_test_pre = np.array(y_test_pre)
    sdata[saveindex] = y_test_pre
    sdata.to_csv(savepath,index =False)
# In[ ]:
def splitdata(data,sequence_length,horizon):
    ydata = data
    all_data = []
    for z in range(len(ydata) - sequence_length-horizon+1):
        all_data.append(ydata[z: z + sequence_length])
    # In[46]:
    all_data = np.array(all_data)
    y_data = np.array(ydata)[-len(all_data):].reshape(len(all_data),1)
#%%
    all_data = np.hstack((all_data,y_data))
#%% 读取特征项
    # ex = data.iloc[sequence_length-horizon+1:-horizon,1:-1]
    # ex = data.iloc[sequence_length-horizon:-horizon,1:-1]
# In[]
##%% 拼接
    # new_data = np.hstack((np.array(ex),np.array(all_data)))
# In[47]:
#     all_data = np.array(new_data)

    row = round(0.2 * int(data.shape[0]))
    #creating training data
    x_train_initial = all_data[:-int(row), :-1]
    x_test_initial = all_data[-int(row):, :-1]
    y_train_initial = all_data[:-int(row), -1]
    y_test_initial = all_data[-int(row):, -1]

    initialdata = pd.DataFrame(all_data)
    initialdata.to_csv('Initial_data.csv', index=False)
    return x_train_initial,x_test_initial,y_train_initial,y_test_initial
# In[156]:
#标准化处理
def standata(x_train_initial,x_test_initial,y_train_initial,y_test_initial):
    x_scaler = StandardScaler()
    y_scaler = StandardScaler()
    x_scaled = x_scaler.fit(x_train_initial)
    x_train = x_scaler.transform(x_train_initial)
    x_test = x_scaler.transform(x_test_initial)
    
    y_scaler = y_scaler.fit(y_train_initial.reshape(-1,1))
    y_train = y_scaler.transform(y_train_initial.reshape(-1,1))
    y_test = y_scaler.transform(y_test_initial.reshape(-1,1))

    return x_train,x_test,y_train,y_test

def iverse_data(y_train_initial,pre,y_test):
    
    y_scaler = StandardScaler()
    y_scaler = y_scaler.fit(y_train_initial.reshape(-1,1))
    y_test_pre = y_scaler.inverse_transform(pre.reshape(-1, 1) )
    y_test_rel = y_scaler.inverse_transform(y_test)
    return y_test_rel,y_test_pre
